package org.wmq.skyserver.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.wmq.skycommon.context.BaseContext;
import org.wmq.skycommon.pojo.DTO.ShoppingCartDTO;
import org.wmq.skycommon.pojo.entity.Dish;
import org.wmq.skycommon.pojo.entity.ShoppingCart;
import org.wmq.skycommon.utils.JwtUtil;
import org.wmq.skyserver.mapper.DishMapper;
import org.wmq.skyserver.mapper.SetmealDishMapper;
import org.wmq.skyserver.mapper.ShoppingCartMapper;
import org.wmq.skyserver.service.ShoppingCartService;

import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = this.shoppingCartMapper.list(shoppingCart);
        if (list != null && list.size() > 0) {
            ShoppingCart result = list.get(0);
            result.setNumber(result.getNumber() + 1);
            this.shoppingCartMapper.updateNumberById(result);
            return;
        }
        if (shoppingCartDTO.getDishId() == null){
            Dish dish = this.dishMapper.getById(shoppingCartDTO.getDishId());
            shoppingCart.setUserId(dish.getId());
        }else{

        }
        this.shoppingCartMapper.insert(shoppingCart);


    }

    @Override
    @Cacheable(cacheNames = "shoppingCart", key = "#userId")
    public List<ShoppingCart> showShoppingCart(Long userId) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        return this.shoppingCartMapper.list(shoppingCart);
    }

    @Override
    @CacheEvict(cacheNames = "shoppingCart",key = "#userId")
    public void clean(Long userId) {
        this.shoppingCartMapper.delete(userId);
    }
}
